import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {AirQualityDataService} from "./air-quality-data.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {TableUtil} from "../../../../util/table-util";

declare var $;
declare var moment;

@Component({
  selector: 'app-air-quality-data',
  templateUrl: './air-quality-data.component.html',
  styleUrls: ['./air-quality-data.component.css']
})
export class AirQualityDataComponent implements OnInit {
  config;tableDataObj;siteObj;table;
  constructor(
    private pageSubject : PageSubject,
    private AirQualityDataService : AirQualityDataService,
    private responseUtil :ResponseUtil,
    private tableUtil:TableUtil,
    private dialogService: OneDialogService,
  ) { }

  ngOnInit() {
    this.pushPage();
    this.siteButtonData();
  }

  //面包屑导航
  pushPage() {
    let path = new Path("数据查询", "");
    this.pageSubject.pushPage("空气质量", "", path);
  }

//   站点按钮数据
  siteButtonData(){
    this.AirQualityDataService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result,this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点按钮
  siteButtonDataDataTree(data){
    let siteHtml = "";
    let localSite = [
      {"name":"nationalSite","className":"national","type":"national","chinese":"国控站"},
      {"name":"provinceSite","className":"province","type":"province","chinese":"省控站"},
      {"name":"smallAirSite","className":"small","type":"smallAir","chinese":"微型站"}
      ];
    $.each(localSite,function (j,siteList) {
      $.each(data,function (i,list) {
        if(list==siteList.name){
          siteHtml+='<div class="btn btn-default '+siteList.className+'" id="'+siteList.name+'" data-type="national">'+siteList.chinese+'</div>';
        }
      });
    });
    if(siteHtml){
      $(".user_site_button").html(siteHtml);
      $(".user_site_button").find(".btn:first").addClass("active");
      //加载其他数据
      this.initTime();
      this.initevent();
      this.tableDataObj = {"pointType":$(".user_site_button").find(".btn:first").attr("id"),"dataType":"hourData","dataCalculateType":"realTimeData","startTime":moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00:00","endTime":moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00:00"};
      this.tableContentData(this.tableDataObj);
      this.siteObj = {"pointType":"smallAirSite","dataType":"dayData","dataCalculateType":"realTimeData","startTime":moment().subtract(2,"d").format("YYYY-MM-DD")+" 00:00:00","endTime":moment().subtract(1,"d").format("YYYY-MM-DD")+" 00:00:00","pointCode":" "};
      this.siteListContentData(this.siteObj);
      this.dateChange();
      this.initSite();
    }else{
      $(".one-content").html("暂无数据");
    }

  };

  //表格数据
  tableContentData(obj){
    this.AirQualityDataService.getAirQualityData(obj).subscribe(
      result => this.responseUtil.success(result,this.tableContentDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private tableContentDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.tableContentDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private tableContentDataTree(data){
    $(".one-data-loadState").hide();
      this.tableContent(data);
  }

  //表格
  tableContent(datas){
  $(".one-table-area").html('<table class="table table-striped" id="airQualityTable"></table>');
    this.table=this.tableUtil.load("airQualityTable",{
      columns: [
        {
          field: 'index',
          title: '排名',
          width:35
        }, {
          field: 'siteName',
          title: '站点名称',
          align:"left",
          halign:"center",
          width:90
        }, {
          field: 'monitorTime',
          title: '监测时间',
          width:110,
          align:"left",
          halign:"center"
        }, {
          field: 'compositeValue',
          title: '综合指数',
          width:60,
          align:"right",
          halign:"center"
        }, {
          field: 'aqi',
          title: 'AQI',
          formatter:this.AQIColor,
          width:50,
          align:"center",
          halign:"center"
        }, {
          field: 'pm10',
          title: 'PM10',
          formatter:this.pm10color,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'pm25',
          title: 'PM2.5',
          formatter:this.pm25color,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'so2',
          title: 'SO<sub>2</sub>',
          formatter:this.so2color,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'no2',
          title: 'NO<sub>2</sub>',
          formatter:this.no2color,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'co',
          title: 'CO',
          formatter:this.cocolor,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'o3',
          title: 'O<sub>3</sub>',
          formatter:this.o3color,
          width:50,
          align:"right",
          halign:"center"
        }, {
          field: 'aqiLevelType',
          title: '等级',
          width:60,
          align:"left",
          halign:"center"
        }, {
          field: 'pollutant',
          title: '首要污染物',
          width:110,
          align:"left",
          halign:"center"
        }
      ],
      data:datas,
      pagination :true,
      paginationLoop: false,
      striped :true,
      paginationPreText : "上一页",
      paginationNextText :"下一页",
      undefinedText : " ",
      height:$(window.innerHeight)[0]-300,
      pageSize:15,
      pageList :[10,15,20]
    });
  }

  //表格样式修改
  private  AQIColor(value, row, index){
    if(value){
        if(value<=50){
          return '<span class="user_air_table one-bg-level1">'+value+'</span>';
        }else if(value<=100){
          return '<span class="user_air_table one-bg-level3">'+value+'</span>';
        }else if(value<=150){
          return '<span class="user_air_table one-bg-level4">'+value+'</span>';
        }else if(value<=200){
          return '<span class="user_air_table one-bg-level5">'+value+'</span>';
        }else if(value<=300){
          return '<span class="user_air_table one-bg-level6">'+value+'</span>';
        }else if(value<=500){
          return '<span class="user_air_table one-bg-level7">'+value+'</span>';
        }
    }else{
      return '<span>-</span>';
    }
  }
  private  pm10color(value, row, index){
    if(value){
        if(value>150){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
    }else{
      return '<span>-</span>';
    }
  }
  private  pm25color(value, row, index){
    if(value){
        if(value>75){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
    }else{
      return '<span>-</span>';
    }
  }
  private  so2color(value, row, index){
    let dataTypeId = $(".dataType").find(".active").attr("id");
    if(value){
      if(dataTypeId == "dayData"){
        if(value>150){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }else{
        if(value>500){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }
    }else{
      return '<span>-</span>';
    }
  }
  private  no2color(value, row, index){
    let dataTypeId = $(".dataType").find(".active").attr("id");
    if(value){
    if(dataTypeId == "dayData"){
      if(value>80){
        return '<span class="user_color_red">'+value+'</span>';
      }else{
        return '<span>'+value+'</span>';
      }
    }else{
      if(value>200){
        return '<span class="user_color_red">'+value+'</span>';
      }else{
        return '<span>'+value+'</span>';
      }
    }
    }else{
      return '<span>-</span>';
    }
  }
  private  cocolor(value, row, index){
    let dataTypeId = $(".dataType").find(".active").attr("id");
    if(value){
      if(dataTypeId == "dayData"){
        if(value>4){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }else{
        if(value>10){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }
    }else{
      return '<span>-</span>';
    }
  }
  private  o3color(value, row, index){
    let dataTypeId = $(".dataType").find(".active").attr("id");
    if(value){
      if(dataTypeId == "dayData"){
        if(value>160){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }else{
        if(value>200){
          return '<span class="user_color_red">'+value+'</span>';
        }else{
          return '<span>'+value+'</span>';
        }
      }
    }else{
      return '<span>-</span>';
    }
  }


  //下拉列表数据
  siteListContentData(obj){
    this.AirQualityDataService.getAirQualityData(obj).subscribe(
      result => this.responseUtil.success(result,this.siteListContentDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteListContentDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteListContentDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private siteListContentDataTree(data){
    if(data == null){
      $(".no-records-found>td").html("暂无数据");
    }else{
      console.log("表格数据加载成功");
      $(".one-data-loadState").hide();
      this.dropDownData(data);
    }
  }

  dropDownData(data) {
    let siteData = "";
    $.each(data, function (i, list) {
      siteData += '<li><label><input type="checkbox" name="siteName" id="' + list.siteCode + '">' + list.siteName + '</label></li>';
    })
    if(siteData){
      $("#industrySite").html(siteData);
    }else{
      $("#industrySite").html("暂无数据");
    }
    //改变input样式
    $('input').iCheck({
      checkboxClass: 'icheckbox_minimal-green',
      radioClass: 'iradio_minimal-green',
      increaseArea: '20%' // optional
    });
    //点击下拉列表中的元素
    $('.list-inline input').on('ifChecked', function(e){
      console.log(1)
      var text = $(this).parent().parent().text();
      var id = $(this).attr("id");
      var btnPoint = $(this).parent().parent().parent().parent().attr("id");
      var btnHtml = '<div class="btn btn-success" id='+id+' data-point=' +btnPoint+ '>'+text+' <i class="glyphicon glyphicon-remove"></i></div>';
      $(".one-inline-container").append(btnHtml);
    }).on('ifUnchecked', function(e){
      var text = $.trim($(this).parent().parent().text());
      $(".one-inline-container>.btn").each(function(){
        var btnText = $.trim($(this).text());
        if(btnText==text){
          $(this).remove();
        }
      });
    });
  }

  initSite(){
    //点击站点列表
    $(".one-inline-btn").click(function(){
      $(this).find(".dropdown-menu").show();
    }).mouseleave(function(){
      $(this).find(".dropdown-menu").hide();
    });

    //点击站点列表中的删除图标
    $(".one-inline-container").on("click",".btn>.glyphicon-remove",function(){
      $(this).parent().remove();
      if($(".one-inline-container>.btn").length<5){
        $('.list-inline input').iCheck('enable');
      }else{
        $('.list-inline .icheckbox_minimal-green:not(.checked) input').iCheck('disable');
      }
      var btnId = $(this).parent().attr("id");
      $(".dropdown-menu label").each(function(){
        var  id = $(this).find("input").attr("id");
        if( btnId == id){
          $(this).find("input").iCheck('uncheck');
        }
      });
    });

    //查询站点
    $("#searchPollute").bind("input propertychange",function () {
      let searchSiteVal = $("#searchPollute").val();
      if(searchSiteVal){
        $(".dropdown-menu label").each(function(){
          var text = $(this).text();
          if(text.indexOf(searchSiteVal)!=-1){
            $(this).parent().show();
          }else{
            $(this).parent().hide();
          }
        })
      }else{
        $(".dropdown-menu label").parent().show();
      }
    })







  }


  //初始化时间插件
  initTime(){
    let timeData = moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00"
    this.config = {
      timePicker:true,
      timePickerIncrement:5,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      locale:{
        format:"YYYY-MM-DD HH:00",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: timeData,
      endDate: timeData,
      maxDate: timeData
    };
    $("#airQualityDate").daterangepicker(this.config);
    $(".one-data-loadState").show();
  }

  //点击查询数据类型的查询函数
  clickDataType(dataType){
    let pointCodes=null ;
    let startTime =  $.trim($("#airQualityDate").val().split("至")[0]);
    let endTime = $.trim($("#airQualityDate").val().split("至")[1]);
  startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
  endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    let  pointType = $(".site").find(".active").attr("id");
    if(pointType == "smallAirSite"){
      pointCodes =$(".airQualityDateArea").attr("id");
    }
  var obj = {"startTime":startTime,"endTime":endTime,"pointType":pointType,"dataType":dataType};
}

  //点击站点类型的查询函数
  clickSiteType(pointType){
    let startTime =  $.trim($("#airQualityDate").val().split("至")[0]);
    let endTime =  $.trim($("#airQualityDate").val().split("至")[1]);
  startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
  endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    var dataType=$(".dataType").find(".active").attr("id");
    let dataCalculateType;
    if(dataType=="addUpTimeData"){
      dataCalculateType="addUpTimeData"
      dataType = "hourData";
    }else{
      dataCalculateType="realTimeData"
    }
  var obj = {"startTime":startTime,"endTime":endTime,"pointType":pointType,"dataCalculateType":dataCalculateType};

}

  //点击查询的函数
  dateChange(){
    $(".one-table-area").html('<table class="table table-striped" id="airQualityTable"></table>');
    $(".one-data-loadState").show();
    let pointType=$(".site").find(".active").attr("id");
    let  dataType=$(".dataType").find(".active").attr("id");
    let startTime =  $.trim($("#airQualityDate").val().split("至")[0]);
    let endTime =  $.trim($("#airQualityDate").val().split("至")[1]);
    let dataCalculateType;
    startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
    endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
    if(dataType=="addUpTimeData"){
      dataType="hourData";
      dataCalculateType="addUpTimeData"
    }else{
      dataType=dataType;
      dataCalculateType="realTimeData"
    }
    //需要修改pointCode
    //var pointCode = $(".airQualityDateArea").attr("id");

    let checkedSiteListObj = [];
    $(".one-inline-container>.btn").each(function(){
      var id = $(this).attr("id");
      checkedSiteListObj.push(id);
    });
    console.log(checkedSiteListObj);
    let pointCode = checkedSiteListObj.join(",");

    let  changeData;
    if(pointType =="smallAirSite"){
      changeData= {"pointType":pointType,"dataType":dataType,"dataCalculateType":dataCalculateType,"startTime":startTime,"endTime":endTime,"pointCode":pointCode};
    }else{
      changeData= {"pointType":pointType,"dataType":dataType,"dataCalculateType":dataCalculateType,"startTime":startTime,"endTime":endTime};
    }
    this.tableContentData(changeData);
  }

//点击查询数据类型的查询函数
  initevent(){
    $(".user_dropdown").hide();
    $(".search").click(function(e){
      this.dateChange();
    }.bind(this));
    $(".national").click(function(e){
      //$(".user_dropdown").hide();
      $(".smallSiteList").hide()
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickSiteType("nationalPoint");

    }.bind(this));
    $(".province").click(function(e){
      //$(".user_dropdown").hide();
      $(".smallSiteList").hide()
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickSiteType("provincePoint");
    }.bind(this));
    $(".small").click(function(e){
      //$(".user_dropdown").show();
      $(".smallSiteList").show()
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickSiteType("smallAirPoint");
    }.bind(this));
    $(".days").click(function(e){
      this.config.locale.format="YYYY-MM-DD";
      this.config.timePicker=false;
      this.config.startDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      this.config.maxDate= moment().subtract(1,"d").format("YYYY-MM-DD");
      $("#airQualityDate").daterangepicker(this.config).removeAttr("disabled");
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickDataType("dayData");
    }.bind(this));
    $(".fiveminute").click(function(e){
      this.config.locale.format="YYYY-MM-DD HH:mm";
      this.config.timePicker=true;
      this.config.startDate = moment().subtract(21,"m").format("YYYY-MM-DD HH:mm");
      this.config.endDate = moment().subtract(1,"m").format("YYYY-MM-DD HH:mm");
      this.config.maxDate= moment().subtract(1,"m").format("YYYY-MM-DD HH:mm");
      $("#airQualityDate").daterangepicker(this.config).removeAttr("disabled");
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickDataType("minuteData");
    }.bind(this));
    $(".hours").click(function(e){
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.timePicker=true;
      this.config.startDate = moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.maxDate= moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      $("#airQualityDate").daterangepicker(this.config).removeAttr("disabled");
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      this.clickDataType("hourData");
    }.bind(this));
    $(".count").click(function(e){
      $("#airQualityDate").val(moment().format("YYYY-MM-DD")+" 00:00 至 "+moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00").attr("disabled",true);
      $(e.target).addClass("active").siblings(".active").removeClass("active");
      let startTime =$.trim($("#airQualityDate").val().split("至")[0]);
      let endTime = $.trim($("#airQualityDate").val().split("至")[1]);
      startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
      endTime+=endTime.split(" ").length==1?" 00:00:00":":00";
      let pointType = $(".site").find(".active").attr("id");
      var obj = {"format":"json","pointType":pointType,"dataCalculateType":"addUpTimeData","startTime":startTime,"endTime":endTime};
    }.bind(this));


    //添加导出按钮
    $(function(){
      $(".one-btn-data-type:eq(1)").append("<div class='pull-right'><button class='btn btn-success export'>导出为Excel</button></div>");
      $(".export").click(function(){
        let checkedSiteListObj = [];
        $(".one-inline-container>.btn").each(function(){
          var id = $(this).attr("id");
          checkedSiteListObj.push(id);
        });
        console.log(checkedSiteListObj);
        let pointCode = checkedSiteListObj.join(",");

        var pointType=$(".site").find(".active").attr("id");
        var dataType=$(".dataType").find(".active").attr("id");
        var startTime =  $.trim($("#airQualityDate").val().split("至")[0]);
        var endTime =  $.trim($("#airQualityDate").val().split("至")[1]);
        startTime+=startTime.split(" ").length==1?" 00:00:00":":00";
        endTime+= endTime.split(" ").length==1?" 00:00:00":":00";
        var dataCalculateType="realTimeData";
        if(dataType=="addUpTimeData"){
          dataType="hourData";
          dataCalculateType="addUpTimeData"
        }else{
          dataType=dataType;
          dataCalculateType="realTimeData";
        }
        var objString = "endTime="+endTime+"&startTime="+startTime+"&pointType="+pointType+"&dataCalculateType="+dataCalculateType+"&dataType="+dataType+"&pointCodes="+pointCode;
        let baseUrl = location.protocol + "//" + location.host + "/";
        console.log(baseUrl+"api/exportExcel/airQuarlityDataExcelExport?format=json&"+objString)
        window.location.href = baseUrl+"api/exportExcel/airQuarlityDataExcelExport?format=json&"+objString;
      })
    });


  }

}
